package com.ayf.payment.game.api.service.payment.huyu;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.bean.BaseResData;
import com.ayf.payment.game.api.dto.MerchantCommonDTO;
import com.ayf.payment.game.api.dto.OrderAndMerchantDTO;
import com.ayf.payment.game.api.dto.platform.MerchantPaymentProductDTO;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.entity.Partition;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.httpclient.HttpUtils;
import com.ayf.payment.game.api.service.payment.IPaymentService;
import com.ayf.payment.game.api.service.payment.huyu.util.HuYuSignUtil;
import com.ayf.payment.game.api.type.OrderStatus;
import com.ayf.payment.game.api.utils.BigDecimalUtil;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class HuYuPaymentService extends IPaymentService {

    @Override
    public Map<String, Object> paymentUtil(Order order, Partition partition, String orderCreateStr, String traceId, String redirectUrl) {
        Map<String, Object> map=new HashMap<>();
        MerchantCommonDTO merchantDTO = merchantService.getMerchantCommon(partition.getMerchantId());
        MerchantPaymentProductDTO merchantPaymentProductDTO = systemInitialization.productDTO(order.getPayTypeId());
        PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(merchantPaymentProductDTO.getcId());
        BigDecimal actualOrderAmt = getActualOrderAmt(order.getAmount(),paymentChannelDTO.getId(),partition.getMerchantId());
        BaseResData baseResData = orderCreate(traceId,order,paymentChannelDTO,redirectUrl,actualOrderAmt,merchantPaymentProductDTO.getBusinessCode(),merchantDTO);
        String orderCreateUrl = "";
        if (baseResData.isProcessing()){
            LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 互娱下单失败 请求接口成功，接口响应超时", traceId, order.getMerchantId(), order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        BigDecimal randomAmt = BigDecimal.ZERO;
        String dataType = "";
        if (baseResData.isSuccess()) {
            String rpsData = baseResData.getData();
            JSONObject jsonData = JSONObject.parseObject(rpsData);
            String ret_msg = jsonData.getString("message");
            String status = jsonData.getString("status");
            if ("1".equals(status)){
                orderCreateUrl = jsonData.getString("data");
                if (StringUtils.isEmpty(orderCreateUrl)){
                    LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 互娱下单失败 请求接口成功，接口返回报文 data 为空",traceId,order.getMerchantId(), order.getMerchantOrderNo());
                    throw new NullSetException(traceId + "下单失败，请稍后重试！");
                }
                String rand_fee = jsonData.getString("floatmoney");
                // 1:页面输出,2:URL跳转,3:二维码串,4:二维码图片地址,5:base64图片码
                dataType = jsonData.getString("datatype");
                if (StringUtils.isNotEmpty(rand_fee)){
                    randomAmt = BigDecimalUtil.amtStrToBigdecimal(rand_fee);
                }
            } else {
                LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 互娱下单失败 请求接口成功，接口返回失败 Code:{} Message:{}",traceId,order.getMerchantId(), order.getMerchantOrderNo(),status,ret_msg);
                throw new NullSetException(traceId + "下单失败，请稍后重试！");
            }
        } else {
            LogPortal.error("{} 商户ID[{}] 商户订单号[{}] 互娱下单失败 请求接口失败 Code:{} Message:{}",traceId,order.getMerchantId(), order.getMerchantOrderNo(),baseResData.getRespCode(),baseResData.getRespMsg());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!"5".equals(dataType)){
            LogPortal.info("{} 商户ID[{}] 商户订单号[{}] 互娱下单 通道支付URL[{}]", traceId, order.getMerchantId(), order.getMerchantOrderNo(),orderCreateUrl);
        }
        order.setRandomAmt(randomAmt);
        order.setPayChannleName(paymentChannelDTO.getName());
        order.setPayChannleId(paymentChannelDTO.getId());
        order.setPayTypeId(merchantPaymentProductDTO.getProductId());
        order.setPayTypeName(merchantPaymentProductDTO.getProductName());
        order.setMerchantIncome(BigDecimal.ZERO);
        order.setPlatformIncome(BigDecimal.ZERO);
        order.setFee(BigDecimal.ZERO);
        order.setChannelIncome(BigDecimal.ZERO);
        orderMapper.insertSelective(order);
        if ("3".equals(dataType)){
            if (StringUtils.isNotEmpty(orderCreateUrl)) {
                redisCacheUtil.setObjectToCacheDelaySeconds(order.getMerchantOrderNo(), orderCreateUrl, 300L);
            }
            map.put("code","004");
            map.put("url", orderCreateUrl);
        }else if ("2".equals(dataType)){
            map.put("code","003");
            map.put("RedirectUrl",orderCreateUrl);
        }else if ("1".equals(dataType)){
            map.put("code","002");
            map.put("htmlMsg",orderCreateUrl);
        }else if ("4".equals(dataType)||"5".equals(dataType)){
            map.put("code","005");
            map.put("url",orderCreateUrl);
        }
        map.put("merchantOrderNo", order.getMerchantOrderNo());
        map.put("amount",order.getAmount());
        map.put("randomAmt",BigDecimalUtil.yuanToFen(randomAmt).add(BigDecimalUtil.yuanToFen(actualOrderAmt.subtract(order.getAmount()))));//单位 分
        map.put("rechargeNumber", order.getRechargeNumber());
        map.put("partitionName", order.getPartitionName());
        if ("3".equals(dataType)||"4".equals(dataType)||"5".equals(dataType)){
            redisCacheUtil.setObjectToCacheDelaySeconds("PayBean_".concat(order.getMerchantOrderNo()),map, 300L);
        }
        return map;
    }


    private BaseResData orderCreate(String traceId, Order order, PaymentChannelDTO paymentChannelDTO, String redirectUrl, BigDecimal actualOrderAmt, String businessCode, MerchantCommonDTO merchantDTO){
        String methodName = "互娱下单";
        String KeyValue = paymentChannelDTO.getChannelKey();
        String parter = paymentChannelDTO.getAccountNumber();
        String returnUrl=paymentChannelDTO.getReturnUrl();
        String AuthorizationURL = paymentChannelDTO.getPaymentUrl();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} 失败，通道下单地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        if (StringUtils.isEmpty(returnUrl)){
            LogPortal.error("{} 失败，异步通知地址不能为空，订单号:{}",traceId,order.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!returnUrl.endsWith("/")){
            returnUrl=returnUrl.concat("/");
        }
        AuthorizationURL=AuthorizationURL.concat("online/gateway");
        Map<String, String> reqParam = new LinkedHashMap<>();
        reqParam.put("version","3.1.0");
        reqParam.put("method","online.interface");
        reqParam.put("partner",parter);
        reqParam.put("banktype",getPayCode(businessCode));
        reqParam.put("paymoney", String.valueOf(actualOrderAmt));
        reqParam.put("ordernumber",order.getMerchantOrderNo());
        reqParam.put("callbackurl",returnUrl.concat("gameapip/v/huyu/pay/notify"));
        reqParam.put("clientip",order.getClientIp());
        String sign= HuYuSignUtil.getSign(traceId,methodName,reqParam,KeyValue);
        reqParam.put("sign",sign);

        reqParam.put("hrefbackurl",returnUrl.concat("gameapip/v/huyu/pay/returns"));
        reqParam.put("attach",redirectUrl);
        BaseResData baseResData = HttpUtils.sendPostForm(traceId,methodName,AuthorizationURL,reqParam);
        return baseResData;
    }


    @Override
    public void queryPayOrder(OrderAndMerchantDTO dto, String traceId) {
        String methodDesc = "互娱订单查询";
        PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(dto.getPayChannleId());
        BaseResData baseResData = orderQuery(traceId,methodDesc,paymentChannelDTO,dto);
        if (baseResData.isProcessing()){
            return;
        }
        if (baseResData.isSuccess()){
            String result = baseResData.getData();
            JSONObject jsonData = JSONObject.parseObject(result);
            String code = jsonData.getString("status");// 查询状态,1:成功,0:失败
            String ret_msg = jsonData.getString("message");
            if ("1".equals(code)){
                // 订单状态,0:支付中,1:成功,2:失败
                String status = jsonData.getString("tradestate");
                String merchantOrderNo = jsonData.getString("ordernumber"); // 商户订单号
                String channelOrderNo = jsonData.getString("sysnumber"); // 支付接口订单号
                Order order = orderService.selectByMerchantOrderNo(merchantOrderNo);
                if (order == null) {
                    LogPortal.error("{} {} 商户订单号[{}]在我方系统查询不到", traceId,methodDesc,merchantOrderNo);
                    return;
                }
                if (StringUtils.isEmpty(status) || "0".equals(status)){
                    LogPortal.error("{} {} 商户订单号[{}] 渠道返回状态不明确 返回状态:{}", traceId,methodDesc,merchantOrderNo,status);
                    return;
                }
                OrderStatus orderStatus= OrderStatus.PROCESSING;
                if ("1".equals(status)){ // 成功
                    orderStatus= OrderStatus.SUCCESS;
                }
                if (OrderStatus.PROCESSING.equals(order.getOrderStatus()) && !orderStatus.equals(OrderStatus.PROCESSING)) {
                    order.setOrderStatus(orderStatus);
                    order.setChannelRpsMsg("支付成功");
                    if (StringUtils.isNotEmpty(channelOrderNo)){
                        order.setOrderNo(channelOrderNo);
                    }
                    orderService.paymentOrder(order, new JSONObject());
                    if (OrderStatus.SUCCESS.equals(order.getOrderStatus())) {
                        orderService.orderToGetWay(order);
                        wxSendMsgUtils.rechargeSuccess(order);
                    }
                }
            } else {
                LogPortal.error("{} {} 查询通道返回错误码:{} 错误描述:{}",traceId,methodDesc,code,ret_msg);
            }
        }
    }

    private BaseResData orderQuery(String traceId, String methodName, PaymentChannelDTO paymentChannelDTO, OrderAndMerchantDTO dto){
        String AuthorizationURL = paymentChannelDTO.getPaymentUrl();
        String orderNo = dto.getMerchantOrderNo();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} 失败，通道下单地址不能为空，订单号:{}",traceId,dto.getMerchantOrderNo());
            throw new NullSetException(traceId + "下单失败，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        AuthorizationURL=AuthorizationURL.concat("online/gateway");

        Map<String, String> reqParam = new LinkedHashMap<>();
        reqParam.put("version","3.0");
        reqParam.put("method","online.query");
        reqParam.put("partner",paymentChannelDTO.getAccountNumber());
        reqParam.put("ordernumber",orderNo);
        reqParam.put("sysnumber","");
        String sign= HuYuSignUtil.getSign(traceId,methodName,reqParam,paymentChannelDTO.getChannelKey());
        reqParam.put("sign",sign);
        BaseResData result = HttpUtils.sendPostForm(traceId,methodName,AuthorizationURL,reqParam);
        return result;
    }

    private String getPayCode(String code){
        if("ALIPAY".equals(code) || "ANTCREDITPAY".equals(code)){
            return "ALIPAY";
        } else if("WECHAT".equals(code)){
            return "WEIXIN";
        } else {
            throw new NullSetException("该通道不支持充值，请更换其他通道充值！");
        }
    }

    private static void testOrderCreate(){
        PaymentChannelDTO paymentChannelDTO = getTestPaymentChannelDTO();
        Order order = new Order();
        Date currentDate = DateUtils.getNowDate();
        String orderCreateStr = DateUtils.dateToString(currentDate, DateUtils.formatPattern_full_03);
        String orderNo = "M" + orderCreateStr + SnowFlakeUtils.getUniqueId();
        order.setMerchantOrderNo(orderNo);
        order.setCreateTime(currentDate);
        order.setAmount(BigDecimal.valueOf(1));
        order.setMerchantId(1000);
        order.setClientIp("127.0.0.1");
        String traceId = SnowFlakeUtils.getTraceId28();
        String redirectUrl = "http://uatxy.xyouplay.com";
        String bussinessCode = "ALIPAY";

        MerchantCommonDTO merchantDTO = new MerchantCommonDTO();
        HuYuPaymentService xinYou2PaymentService = new HuYuPaymentService();
        BaseResData baseResData = xinYou2PaymentService.orderCreate(traceId,order,paymentChannelDTO,redirectUrl,order.getAmount(),bussinessCode,merchantDTO);
        System.out.println("互娱下单返回报文:"+ JSONObject.toJSONString(baseResData));
    }

    private static void testOrderQuery(){
        PaymentChannelDTO paymentChannelDTO = getTestPaymentChannelDTO();
        String traceId = SnowFlakeUtils.getTraceId28();

        OrderAndMerchantDTO dto = new OrderAndMerchantDTO();
        dto.setMerchantId(1000);
        dto.setMerchantOrderNo("M".concat(traceId));
        HuYuPaymentService xingYou2PaymentService = new HuYuPaymentService();
        BaseResData result = xingYou2PaymentService.orderQuery(traceId,"互娱订单查询",paymentChannelDTO,dto);
        System.out.println("互娱订单查询返回结果:"+result);
    }

    private static PaymentChannelDTO getTestPaymentChannelDTO(){
        PaymentChannelDTO paymentChannelDTO = new PaymentChannelDTO();
        paymentChannelDTO.setPaymentUrl("http://tj.shcqhy.com");
        paymentChannelDTO.setReturnUrl("http://uatxy.xyouplay.com");
        paymentChannelDTO.setChannelKey("336f83904b7de0da8c733c913cd195d5");
        paymentChannelDTO.setAccountNumber("16980");// 商户ID
        return paymentChannelDTO;
    }

    public static void main(String[] args) {
        testOrderCreate();
//        testOrderQuery();
    }

}
